package com.salary;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.salary.service.FileRead;
import com.salary.utils.Zip;
import com.salary.utils.FileUtil;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		long sumSize = 0;
		String ip = request.getRemoteAddr();
		Logger log = Logger.getLogger("record");
		ServletContext context = request.getServletContext();
		String contextpath = context.getRealPath("/");
		String textname = "";
		List<String> excelname = new ArrayList<String>();
		// 获取毫秒时间生成 特定文件夹
		long l = System.currentTimeMillis();
//		System.out.println("时间：" + l);
		// 反转斜杠
		Pattern p = Pattern.compile("\\\\");
		Matcher m;
		m = p.matcher(contextpath);
		contextpath = m.replaceAll("/");
		String filespath = contextpath + "files/time_" + l + "/";
		File dir = FileUtil.createDir(filespath);
		response.setContentType("text/plain;charset=utf-8");
		try {
			DiskFileItemFactory diskFactory = new DiskFileItemFactory();
			diskFactory.setSizeThreshold(500 * 1024 * 1024);
			diskFactory.setRepository(new File(contextpath));
			
			ServletFileUpload upload = new ServletFileUpload(diskFactory);
			upload.setFileSizeMax(100 * 1024 * 1024);
			upload.setSizeMax(500 * 1024 * 1024);
			List<FileItem> fileItems = upload.parseRequest(request);
			Iterator<FileItem> iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				long size = item.getSize();
				sumSize += size;
				if (item.isFormField()) {
				} else {
					String filename = item.getName();
					filename=filename.replaceAll("\\\\", "/");
					filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length());
					String filepath = filespath + filename;
					File uploadFile = new File(filepath);
//					System.out.println("上传文件:"+filename+"；大小："+item.getSize());
					item.write(uploadFile);

					String suffix = filename.substring(filename.lastIndexOf(".")+1, filename.length());
					if ("txt".equals(suffix)) {
						textname = filename;
					} else if ("xls".equals(suffix) || "xlsx".equals(suffix)) {
						excelname.add(filename);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String[] excelpath = new String[excelname.size()];
		for (int i = 0; i < excelname.size(); i++) {
			excelpath[i] = filespath + excelname.get(i);
		}
		String textpath = filespath + textname;
		if (excelpath.length != 0 && !excelpath.equals(null) && textpath.length() != 0 && !textpath.equals(null)) {
			FileRead fileread = new FileRead();
			Map<String, Integer> status = fileread.filter(excelpath, textpath, filespath);
			if (status.size() > 0) {
				String zip = Zip.zip(status, filespath);
				File f = new File(zip);
				InputStream in = new FileInputStream(f);
				BufferedInputStream inf = new BufferedInputStream(in);
				// 需要删除服务器生成的临时文件
				response.reset();
				response.setContentType("application/zip");
				response.setHeader("Content-Disposition",
						"attachment;filename=\"" + URLEncoder.encode("输出生成excel文件.zip", "UTF-8") + "\"");
				// 将网络输入流转换为输出流
				int i = -1;
				while ((i = inf.read()) != -1) {
					response.getOutputStream().write(i);
				}
				response.flushBuffer();
				response.getOutputStream().close();
				in.close();
				inf.close();
			} else {
				System.out.println("筛选失败");
			}
			Runtime rt=Runtime.getRuntime( ); //获得系统的Runtime对象rt 
			System.out.println("---------总内存大小= " + rt.totalMemory()); 
			System.out.println("---------空闲内存大小= " +rt.freeMemory());
			log.info("IP:" + ip + "\r\n传入\""+ (excelname.size() + 1) +"个输入文件,总计大小"+ sumSize +"b;输出" + status.size() + "个excel文件");
		}
		FileUtil.delDir(filespath);
	}

}
